<?php
//智能识别地址信息
//时间：2020-8-28
//作者：sevstudio
//https://ai.baidu.com/tech/nlp_apply/address
//https://ai.baidu.com/ai-doc/NLP/vk6z52h5n
namespace BaiduAddress;

class BaiduAddress{
	
	private $ApiKey;
	private $SecretKey;
	
	public $AccessToken = '';
	public $TokenFile = '';
	
	function __construct($api_key,$secret_key){
		$this->ApiKey = $api_key;
		$this->SecretKey = $secret_key;
		$this->TokenFile = md5($this->ApiKey . $this->SecretKey . '!@$XR@R5x2o') . '.token.php';
	}
	
	public function __log($msg,$title='基础'){
		$dir = __DIR__ . '/log';
		if(!file_exists($dir) && !mkdir($dir,0777,true)) return false;
		$file = $dir . '/' . date('Y-m-d') . '.txt';
		$content = is_string($msg) ? $msg : json_encode($msg, JSON_UNESCAPED_UNICODE);
		$content = '['.date('H:i:s').']['.$title.']' . PHP_EOL . $content . PHP_EOL . PHP_EOL;
		return file_put_contents($file,$content,FILE_APPEND) > 0;
	}
	
	public function getToken(){
		
		$local_token = $this->readToken();
		if($local_token){
			$expires_time = $local_token['expires_time'];
			if($expires_time > time()){
				//没过期
				$this->AccessToken = $local_token['access_token'];
				return true;
			}
		}

		//重新获取
		$url = 'https://aip.baidubce.com/oauth/2.0/token';
		$post_data['grant_type'] = 'client_credentials';
		$post_data['client_id'] = $this->ApiKey;
		$post_data['client_secret'] = $this->SecretKey;
		$o = '';
		foreach ($post_data as $k => $v){
			$o.= "$k=" . urlencode( $v ). "&" ;
		}
		$post_data = substr($o,0,-1);
		
		$res = $this->request_post($url, $post_data);
		$data = json_decode($res,true);
		
		$access_token = '';
		$expires_time = time() - 600;
		if(empty($data)){
			$this->__log($res,'getToken返回错误');
		}else if(isset($data['error']) && isset($data['error_description'])){
			$this->__log($data['error_description'],'getToken返回');
		}else if(isset($data['access_token']) && isset($data['expires_in'])){
			$access_token = $data['access_token'];
			$expires_time += $data['expires_in'];
			$this->saveToken($access_token,$expires_time);
		}else{
			$this->__log($res,'getToken返回错误');
		}
		$this->AccessToken = $access_token;
		return $access_token != '';
	}
	
	private function saveToken($access_token,$expires_time){
		$file = __DIR__ . '/' . $this->TokenFile;
		$data = [
			'access_token' => $access_token,
			'expires_time' => $expires_time, //到期时间
		];
		$content = "<?php\nreturn ". var_export($data,true) .";\n";
		return file_put_contents($file,$content) > 0;
	}
	
	private function readToken(){
		$file = __DIR__ . '/' . $this->TokenFile;
		if(file_exists($file))
			return include $file;
		else
			return null;
	}
	
	public function address($address){
		$url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/address';
		$url.= '?charset=UTF-8&access_token=' . $this->AccessToken;
		$header = [
			'Content-Type:application/json'
		];
		$param = [
			'text' => $address
		];
		$res = $this->request_post($url,json_encode($param,JSON_UNESCAPED_UNICODE),$header);
		//var_dump(json_decode($res,true));
		return json_decode($res,true);
	}
	
	public function request_post($url = '', $param = '',$header = [] ) {
        if (empty($url) || empty($param)) {
            return false;
        }
        
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		if(substr($url,0,5) == 'https'){
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
		}
		if(is_array($header) && count($header)>0){
			curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		}
        $data = curl_exec($curl);//运行curl
        if($data === false){
			$error = curl_error($curl);
			$this->__log($error,'CURL');
		}
		curl_close($curl);
		
        return $data;
    }
}
/*
$hp = new BaiduAddress('AxMc9E5PetyOMwFq1zBkuEC9','0bCwiSUl2j3s27a1dEa9DCA5sGZy30ET');
if($hp->getToken()){
	//$hp->address('广东省深圳市龙华区龙溪山庄e栋610  龚振  15220069393'); //OK
	//$hp->address('徐志强 13054890967  山东省 淄博市 沂源县 历山街道至强科技(县城星河蓝湾西门北03）'); //OK
	$hp->address('陈光乐 15659992990  江西上饶广丰霞峰镇快递自取处');
}else{
	echo 'token failed';
}

array(13) {
  ["province"]=>
  string(9) "广东省"
  ["city"]=>
  string(9) "深圳市"
  ["province_code"]=>
  string(6) "440000"
  ["log_id"]=>
  float(4.0253599071467E+18)
  ["text"]=>
  string(67) "广东省深圳市龙华区龙溪山庄e栋610  龚振  15220069393"
  ["town"]=>
  string(12) "民治街道"
  ["phonenum"]=>
  string(11) "15220069393"
  ["detail"]=>
  string(19) "龙溪山庄e栋610"
  ["county"]=>
  string(9) "龙华区"
  ["person"]=>
  string(6) "龚振"
  ["town_code"]=>
  string(9) "440309003"
  ["county_code"]=>
  string(6) "440309"
  ["city_code"]=>
  string(6) "440300"
}

*/
